<?php
namespace Modules\Product\Http\Controllers\Erp\V1;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use Modules\Product\Entities\Product;
use Modules\Category\Entities\Category;
use Modules\Product\Entities\ProductExt;

use Validator;
use ThrowException;
use DB;

class ProductController extends Controller
{
    public function index(Request $req)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $options = $req->all();

        $options['with'] = ['categories', 'image_tag'];
        $options['with_count'] = ['skus', 'group_prices'];

        $options['order_by'] = [
            'list_weight' => 'desc'
        ];

        $options['only'] = [
            'id',
            'uuid',
            'title',
            'thumb',
            'number',
            'money_price',
            'score_price',
            'stock',
            'list_weight',
            'remark',
            'brokerage_money',
            'brokerage_score',
            'second_brokerage_money',
            'second_brokerage_score',
            'reward_money',
            'reward_score',
            'cover_chip_status',
            'image_tag_id',
            'is_presell',
            'presell_mode',
            'marked_at',
            'order_reward',
            'image_tag' => [
                'title',
                'image',
                'location'
            ],
            'categories' => [
                '*' => [
                    'id',
                    'uuid',
                    'title'
                ]
            ],
            'category_ids',
            'skus_count',
            'group_prices_count',
            'sales',
            'status',
            'created_at',
        ];

        $list = Product::getList($options);

        // $list->each(function ($item) {
        //     $item->stat = $item->stats([
        //         'sales'
        //     ]);
        // });

        return $list->generateListResponse();
    }

    public function show(Request $req, $uuid)
    {
        $builder = Product::where('uuid', $uuid);

        if (strlen($uuid) < 10) {
            $builder = Product::where('id', intval($uuid));
        }

        $item = Product::getEntity([
        	'builder' => $builder,
            'with' => [
                'ext',
                'skus'
            ]
        ]);

        $info = $item->getInfo();

        return [
            'info' => $info
        ];
    }

    public function store(Request $req)
    {

        $rule = [
            'title' => ['required', 'max:100'],
            // 'thumb' => ['required'],
            // 'images' => ['array'],
            // 'skus' => ['required', 'array'],
            // 'sku_attrs' => ['required', 'array'],
            // 'status' => ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $number = $req->input('number');
        $title = $req->input('title');
        
        if ($number && Product::where('number', $number)->first()) {
            ThrowException::Conflict('编号已存在');
        }

        if ($title && Product::where('title', $title)->first()) {
            ThrowException::Conflict('标题已存在');
        }

        $productInfo = [
            'title' => $req->input('title'),
            'thumb' => $req->input('thumb'),
            'number' => $req->input('number'),
            'ean' => $req->input('ean'),
            'money_price' => $req->input('money_price'),
            'score_price' => $req->input('score_price'),
            'category_ids' => $req->input('category_ids'),
            // 'outer_id' => $req->input('outer_id'),
            // 'level1_category_id' => $req->input('level1_category_id'),
            'brand_id' => $req->input('brand_id'),
            'status' => $req->input('status'),
            'tags' => $req->input('tags'),
            'is_need_address' => $req->input('is_need_address', 1),
            'is_free_carriage' => $req->input('is_free_carriage', 0),
            'carriage_type' => $req->input('carriage_type', 1),
            'carriage' => $req->input('carriage'),
            'is_offline_useable' => $req->input('is_offline_useable', 1),
            'is_presell' => $req->input('is_presell', 0),
            'presell_mode' => $req->input('presell_mode', 0),
            'presell_date' => $req->input('presell_date'),
            'category1_id' => $req->input('category1_id'),
            'category2_id' => $req->input('category2_id'),
            'remark' => $req->input('remark'),
        ];

        $ids = [];
        
        // 1级分类的标题
        if ($req->input('category1_title')) {
            $title = $req->input('category1_title');
            $category = Category::where('title', $title)->where('level', 1)->first();

            if (!$category) {
                ThrowException::Conflict('分类《' . $title . '》未创建');
            }

            $productInfo['category1_id'] = $category->id;

            array_push($ids, $category->id);
        }

        // 2级分类的标题
        if ($req->input('category2_title')) {
            $title = $req->input('category2_title');
            $category = Category::where('title', $title)->where('level', 2)->first();

            if (!$category) {
                ThrowException::Conflict('分类《' . $title . '》未创建');
            }

            $productInfo['category2_id'] = $category->id;

            array_push($ids, $category->id);
        }

        $productInfo['category_ids'] = $ids;


        $extInfo = [
            'uuid' => uniqid(),
            'images' => $req->input('images'),
            'normal_attrs' => $req->input('normal_attrs'),
            'sku_attrs' => $req->input('sku_attrs'),
            'page' => $req->input('page')
        ];

        $skuInfos = $req->skus;
        foreach ($skuInfos as $key => $sku) {
            $skuInfos[$key]['uuid'] = uniqid();
        }

        DB::beginTransaction();

        // 创建商品
        $product = Product::create($productInfo);

        // \Log::error($product->id);
        // exit();

        // 保存商品扩展信息
        // $product->ext()->create($extInfo);

        $extInfo['product_id'] = $product->id;
        ProductExt::create($extInfo);

        // 保存商品sku信息
        $product->skus()->createMany($skuInfos);

        $product->updateCategoryRelation();
        $product->updateSalesAndStock();

        DB::commit();

        return [
            'id' => $product->id,
            'uuid' => $product->uuid
        ];
    }

    public function update(Request $req, $uuid)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $item = Product::getEntity([
            'uuid' => $uuid
        ]);

        DB::beginTransaction();

        if ($req->type === 'update') {
            $info = $req->input('attributes');
            $item->update($info);

            $item->updateCategoryRelation();
        }
        elseif ($req->type === 'update_all') {
            $info = $req->input('attributes');

            $keyMap = [
                'title',
                'thumb',
                'number',
                'money_price',
                'score_price',
                'ean',
                'category_ids',
                'brand_id',
                'status',
                'tags',
                'is_presell',
                'presell_mode',
                'presell_date',
                'is_need_address',
                'is_free_carriage',
                'carriage_type',
                'carriage',
                'is_offline_useable',
                'remark',
                'image_tag_id',
            ];

            $productInfo = [];
            foreach ($info as $key => $value) {
                if (in_array($key, $keyMap)) {
                    $productInfo[$key] = $value;
                }
            }

            $item->update($productInfo);

            // 更新 sku 
            // 删除旧sku
            $oldSkuIds = collect($info['skus'])->pluck('id')->all();
            $item->skus()->whereNotIn('id', $oldSkuIds)->delete();

            // 如有原sku id， 更新原sku，否则创建sku
            foreach ($info['skus'] as $sku) {
                if (isset($sku['id']))
                    $item->skus()->where('id', $sku['id'])->first()->update($sku);
                else {
                    $sku['uuid'] = uniqid();
                    $item->skus()->create($sku);
                }
            }

            // 更新ext
            $extInfo = [
                'images' => @$info['images'],
                'normal_attrs' => $info['normal_attrs'],
                'sku_attrs' => $info['sku_attrs'],
                'page' => $info['page']
            ];
            $item->ext->update($extInfo);

            $item->updateCategoryRelation();
            $item->updateSalesAndStock();
        }
        elseif ($req->type === 'put_on' || $req->type === 'put_off') {
            $item->status = $req->type === 'put_on' ? 1 : 0;
            $item->save();
        }
        elseif ($req->type === 'mark') {
            if ($item->marked_at) {
                $item->update([
                    'marked_at' => NULL
                ]);
            }
            else {
                $item->update([
                    'marked_at' => now()
                ]);
            }
        }

        DB::commit();

        return [];
    }

    public function destroy(Request $req, $uuid)
    {
        $rule = [
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $product = Product::getEntity([
            'uuid' => $uuid
        ]);

        $product->ext->delete();
        $product->skus()->delete();

        $product->delete();

        return [];
    }
}
